// import store from '@/store/index2'
// const { state, dispatch, commit } = store
import { useUseStore } from '@/stores/user'
import { message } from '@/utils/ui'

export default (fn, config) => {
  return function (options, callback) {
    const useStore = useUseStore()
    const header = {}

    let token

    if (useStore.token) header.Authorization = token = useStore.token

    options = {
      ...config,
      // 成功消息提示
      successMsg: false,
      // 错误消息提示
      errorMsg: true,
      // 是否需要登录
      needLogin: false,
      // loading
      showLoading: null,
      ...options,
      header: {
        ...header,
        ...config.header,
        ...options.header,
      },
    }

    const { successMsg, errorMsg, needLogin, baseUrl } = options

    // 兼容axios写法
    if (options.params) options.data = options.params

    return new Promise((resolve, reject) => {
      const onSuccess = (res) => {
        if (options.showLoading) uni.hideToast()
        if (options.success) options.success(res)
        if (callback) callback(null, res)
        if (successMsg) message(res.msg)
        resolve(res.data)
      }

      const onFail = (error, res) => {
        if (options.showLoading) uni.hideToast()
        if (options.fail) options.fail(error, res)
        if (callback) callback(error, res)
        if (errorMsg) message(error)
        reject([error, res])
      }

      if (needLogin) {
        if (!token) {
          dispatch('message', '请先登录后使用')
          setTimeout(() => {
            useStore.checkLogin()
          }, 1000)
          return
        }
      }

      if (options.showLoading)
        uni.showToast({
          title: typeof options.showLoading == 'string' ? options.showLoading : '加载中...',
          mask: true,
          duration: 999999,
          icon: 'loading',
        })

      if (options.url && options.url.indexOf('http') != 0) {
        options.url = baseUrl + options.url
      }

      fn({
        ...options,
        success: (res) => {
          if (res.statusCode == 200) {
            let { data } = res

            if (typeof data == 'string') data = JSON.parse(data)

            if (data.code == 0) {
              onSuccess(data)
            } else {
              if (data.code == 401 || data.code == 402) {
                if (options.showLoading) uni.hideToast()
                return useStore.logout()
              }

              onFail(data.msg, data)
            }
          } else {
            onFail('网络或服务器异常，请稍后重试', res)
          }
        },
        fail: (err) => {
          onFail('请求失败', err)
        },
      })
    })
  }
}
